package com.itheima.manage.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.ManageUser;
import com.itheima.commons.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 有NoAuthorization直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }
        // 头中没有数据 返回没有权限 401
        String token = request.getHeader("Authorization");
        token = StrUtil.subSuf(token, 7);
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }
        //解析token
        JWT jwt = JWTUtil.parseToken(token);
        jwt.setKey(Constants.JWT_SECRET.getBytes());

        //判断是否还未过期
        if (!jwt.verify() || !jwt.validate(0)) {
            response.setStatus(401);
            return false;
        }

        Object id = jwt.getPayload("uid");
        Object phone = jwt.getPayload("username");
        ManageUser build = ManageUser.builder().id(Convert.toLong(id)).username(Convert.toStr(phone)).build();
        UserThreadLocal.THREAD_LOCAL_USER.set(build);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.THREAD_LOCAL_USER.remove();
    }
}
